import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { URIConf } from '../config/uri.config';
import 'rxjs/Rx';

declare let $:any;

@Injectable()
export class Service {

    constructor(
        private http: Http
    ) { }
    /**
     * POST 类型的API接口请求
     *
     * @param string uri 接口地址别名参数
     * @param object param 参数对象 {data: 请求参数, success: 成功后回调方法, error: 失败后回调方法}
     */
    protected post(uri : string, param : any ,body:any) {
        const uriConfig = new URIConf();
        const url: string = uriConfig.route(uri);
        const data = $.param(param.data);
        const headers = new Headers({ 'Content-Type':'application/x-www-form-urlencoded' });
        const options = new RequestOptions({ headers:headers });
        let result : any;
        this.http.post(url, data, options)
            .map(response => response.json())
            .subscribe(
                data => result = data,
                err => {
                    console.log('ERROR!!!');
                    param.error();
                },
                () => {
                    param.success(result);
                }
            );
    }
    /**
     * GET 类型的API接口请求
     *
     * @param string uri 接口地址别名参数
     * @param object param 参数对象 {success: 成功后回调方法, error: 失败后回调方法}
     */
    protected get(uri : string, param : any) {
        const uriConfig = new URIConf();
        const url: string = uriConfig.route(uri);
        let result : any;
        this.http.get(url)
        .map(response => response.json())
        .subscribe(
            data => result = data,
            err => {
                console.log('ERROR!!!');
                param.error();
            },
            () => {
                param.success(result);
            }
        );
    }

}